<template>
  <div>
    <span style="top:0;right: 20px;position: absolute;">
      <psi-relative-product
        v-if="financeType == 'projectPurchase' || financeType == 'normalPurchase'"
        :batchProduct="true"
        @value-change="batchProductValue"/>
    </span>
    <div v-for="(item, index) in ruleForm" class="financePurchase">
      <div style="background-color: #e5f7ff;font-size: 13px;margin: 0 10px;margin-top: 15px">
        <span>采购明细 {{ index+1 }}</span>
        <span v-if="index>0" style="float: right;color: #3c8be3;cursor: pointer" @click="spliceSpeci(index)">删除</span>
      </div>
      <div>
        <flexbox direction="column" align="stretch">
          <div class="crm-create-body">
            <el-form :model="item" :rules="rules" ref="productForm" label-position="top" class="crm-create-box">
              <el-form-item prop="name" class="crm-create-item" style="padding-right: 25px;margin-bottom: 0">
                <div
                  slot="label"
                  style="display: inline-block;line-height: 0">
                  <div style="margin:5px 0;font-size:12px;word-wrap:break-word;word-break:break-all;">
                    名称
                  </div>
                </div>
                <xh-input-select
                  v-if="financeType == 'projectPurchase'"
                  :value="item.nameField.value"
                  :item="item.nameField"
                  :pur-data="item"
                  @value-change="fieldValueChange($event, item)"/>
                <psi-relative-product
                  v-else-if="financeType == 'normalPurchase'"
                  :value="item.name == '' ? '' : [{productName:item.name}]"
                  @value-change="oneProductValue($event, item)"/>
<!--                <crm-relative-cell-->
<!--                  v-else-if="financeType == 'normalPurchase'"-->
<!--                  :value="nameField.value"-->
<!--                  :item="nameField"-->
<!--                  @value-change="oneProductValue($event, item)"/>-->
                <el-input v-else v-model="item.name"></el-input>
              </el-form-item>
              <el-form-item prop="spec" class="crm-create-item" style="padding-left: 25px;margin-bottom:0">
                <div
                  slot="label"
                  style="display: inline-block;line-height: 0">
                  <div style="margin:5px 0;font-size:12px;word-wrap:break-word;word-break:break-all;">
                    规格
                  </div>
                </div>
                <el-input v-model="item.spec"></el-input>
              </el-form-item>
              <el-form-item prop="quantity" class="crm-create-item" style="padding-right: 25px;margin-bottom:0">
                <div
                  slot="label"
                  style="display: inline-block;line-height: 0">
                  <div style="margin:5px 0;font-size:12px;word-wrap:break-word;word-break:break-all;">
                    数量
                  </div>
                </div>
                <el-input
                  onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=parseInt(this.value);if(this.value==0){this.value=this.value.replace(/[^1-9]/g,'')};this.value=this.value.replace(/\D/g,'')}"
                  onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=parseInt(this.value);this.value=this.value.replace(/\D/g,'')}"
                  v-model="item.quantity"
                  @input="comTotalPrice"></el-input>
              </el-form-item>
              <el-form-item prop="unit" class="crm-create-item" style="padding-left: 25px;margin-bottom:0">
                <div
                  slot="label"
                  style="display: inline-block;line-height: 0">
                  <div style="margin:5px 0;font-size:12px;word-wrap:break-word;word-break:break-all;">
                    单位
                  </div>
                </div>
                <el-input v-model="item.unit"></el-input>
              </el-form-item>
              <el-form-item prop="purchasePrice" class="crm-create-item" style="padding-right: 25px;margin-bottom:0">
                <div
                  slot="label"
                  style="display: inline-block;line-height: 0">
                  <div style="margin:5px 0;font-size:12px;word-wrap:break-word;word-break:break-all;">
                    采购单价
                  </div>
                </div>
                <el-input
                  v-model="item.purchasePrice"
                  @input="unitPrice(item)"></el-input>
              </el-form-item>
              <el-form-item class="crm-create-item" style="padding-left: 25px;margin-bottom:0">
                <div
                  slot="label"
                  style="display: inline-block;line-height: 0">
                  <div style="margin:5px 0;font-size:12px;word-wrap:break-word;word-break:break-all;">
                    采购参考网址
                  </div>
                </div>
                <el-input v-model="item.purchaseUrl"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </flexbox>
      </div>
    </div>
    <div style="font-size: 15px;margin-bottom: 5px;margin-top: 15px">总价：<span>{{ totalPrice }}</span></div>
    <span style="color: #d0d0d0">如需采购多种产品，请点击“增加明细”</span>
    <div class="addPurchaseDetail">
      <span @click="moreSpeci">+增加明细</span>
    </div>
  </div>
</template>
<script>
import { psiPurchaseEnLeStoDetailList } from '@/api/financemanagement/purchase'
import XhInputSelect from './XhInputSelect'
import CrmRelativeCell from './CrmRelativeCell'
import PsiRelativeProduct from './PsiRelativeProduct'
import PsiRelative from './PsiRelative'
export default {
  name: 'PsiSpecificine',
  components: {
    CrmRelativeCell,
    XhInputSelect,
    PsiRelativeProduct,
    PsiRelative
  },
  props: {
    action: {
      type: Object, default: () => {
        return {
          type: 'ave',
          id: '',
          data:{} // 编辑所需信息
        }
      }
    },
    financeType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      ruleForm: [],
      rules: {
        name: [
          { required: true, message: '请输入采购商品名称', trigger: 'blur' }
        ],
        quantity: [
          { required: true, message: '请输入采购数量', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请输入单位', trigger: 'blur' }
        ],
        purchasePrice: [
          { required: true, message: '请输入采购单价', trigger: 'blur' }
        ]
      },
      totalPrice: 0,
      nameField: {
        data: {
          formType: 'product_all'
        },
        value: ''
      }
    }
  },
  watch: {},
  mounted() {
    this.getDetail()
  },
  methods: {
    getDetail() {
      const reqeust = psiPurchaseEnLeStoDetailList
      const params = {}
      params.purchaseId = this.action.id
      reqeust(params)
        .then(res => {
          if (res.data != '') {
            this.ruleForm = res.data
            for (var i = 0; i < this.ruleForm.length; i++) {
              this.ruleForm[i]['nameField'] = {
                data: {
                  formType: 'product_all'
                },
                value: this.ruleForm[i].productId == null ? '' : [res.data[i]]
              }
            }
            this.comTotalPrice()
          } else {
            this.ruleForm.push({
              name: '', // 名称
              spec: '', // 规格
              quantity: '', // 数量
              unit: '',
              purchasePrice: '',
              purchaseUrl: '',
              nameField: {
                data: {
                  formType: 'product_all'
                },
                value: ''
              }
            })
          }
        })
        .catch(() => {})
    },
    validateField(result) {
      var resultBlack = []
      var trueNum = 0
      this.$refs.productForm.forEach((item, index) => {
        this.$refs.productForm[index].validate(valid => {
          if (valid) {
            // result() // 成功回调
            resultBlack.push(true)
          } else {
            resultBlack.push(false)
            return false
          }
        })
      })
      resultBlack.forEach((el, idx) => {
        if (el) {
          trueNum = trueNum + 1
        }
      })
      if (trueNum === resultBlack.length) {
        result()
      } else {
        return false
      }
    },
    resetForm(formName) { // 重置表单
      this.$refs[formName].resetFields()
    },
    moreSpeci() {
      this.ruleForm.push({
        name: '', // 名称
        spec: '', // 规格
        quantity: '', // 数量
        unit: '',
        purchasePrice: '',
        purchaseUrl: '',
        nameField: {
          data: {
            formType: 'product_all'
          },
          value: ''
        }
      })
    },
    // 减少多规格
    spliceSpeci(index) {
      this.ruleForm.splice(index, 1)
      this.comTotalPrice()
    },
    deliveryStatus(vel, item) {
      // if (this.storehouseVel != '') {
      //   item.storehouse = this.storehouseVel
      // }
    },
    // 计算所有的总价
    comTotalPrice() {
      this.totalPrice = 0
      this.ruleForm.forEach(item => {
        this.totalPrice = this.totalPrice + (item.purchasePrice * item.quantity)
      })
    },
    // 单价框
    unitPrice(item) {
      if (item.purchasePrice != '') {
        item.purchasePrice = item.purchasePrice.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
        item.purchasePrice = item.purchasePrice.replace(/^\./g, '')
        item.purchasePrice = item.purchasePrice.replace(/\.{2,}/g, '.')
        item.purchasePrice = item.purchasePrice.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
        item.purchasePrice = item.purchasePrice.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
      }
      this.totalPrice = 0
      this.ruleForm.forEach(item => {
        this.totalPrice = this.totalPrice + (item.purchasePrice * item.quantity)
      })
    },
    fieldValueChange(el, item) {
      if (typeof el.value == 'string') {
        item.name = el.value
      } else {
        if (el.value.length > 0) {
          item.name = el.value[0].productName
          item.productId = el.value[0].productId
          item.unit = el.value[0].unit
          item.spec = el.value[0].specName
          item.nameField = {
            data: {
              formType: 'product_all'
            },
            value: el.value
          }
        } else {
          item.name = ''
          item.productId = ''
          item.unit = ''
          item.spec = ''
          item.nameField = {
            data: {
              formType: 'product_all'
            },
            value: ''
          }
        }
        this.validateField('name.value')
      }
    },
    oneProductValue(el, item) {
      if (el.value.length > 0) {
        item.name = el.value[0].productName
        item.productId = el.value[0].productId
        item.unit = el.value[0].unit
        item.spec = el.value[0].specName
      } else {
        item.name = ''
        item.productId = ''
        item.unit = ''
        item.spec = ''
      }
    },
    // 批量添加采购明细
    batchProductValue(data) {
      if (this.ruleForm.length === 1 && this.ruleForm[0].name == '') {
        var arry = []
        for (var i = 0; i < data.value.length; i++) {
          arry.push({
            name: data.value[i].productName,
            productId: data.value[i].productId,
            unit: data.value[i].unit,
            spec: data.value[i].specName,
            nameField: {
              data: {
                formType: 'product_all'
              },
              value: [data.value[i]]
            }})
        }
        this.ruleForm = arry
      } else {
        for (var i = 0; i < data.value.length; i++) {
          this.ruleForm.push({
            name: data.value[i].productName,
            productId: data.value[i].productId,
            unit: data.value[i].unit,
            spec: data.value[i].specName,
            nameField: {
              data: {
                formType: 'product_all'
              },
              value: [data.value[i]]
            }})
          // if (this.financeType == 'projectPurchase') {
          //   this.nameField.value = data.value
          // }
        }
      }
    }
  }
}
</script>
<style scoped>
.addPurchaseDetail{
  margin: 10px auto;
}
.addPurchaseDetail>span{
  display: inline-block;
  border: 1px solid #3c8be3;
  color: #3c8be3;
  padding: 5px 10px;
  cursor: pointer;
}
.crm-create-body {
  flex: 1;
}
.crm-create-box {
  display: flex;
  flex-wrap: wrap;
  padding: 0 10px;
}
.crm-create-item {
  flex: 0 0 50%;
  flex-shrink: 0;
  padding-bottom: 10px;
}

</style>
<style>
.financePurchase .crm-create-item .el-form-item__label{
  line-height: 0!important;
  padding-top: 10px;
}
</style>
